const request = require('request');
const {
  mysqlFun
} = require('../mysql/mysql');
exports.postMusic = function (app) {
  // 获取歌曲的id和名字
  app.post("/postMusic", (req, res) => {
    let setImg = encodeURI(req.body.name);
    request("https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=" + setImg + "&type=1&offset=0&total=true&limit=20", function (error, response, body) {
      if (!error && response.statusCode == 200) {
        body = JSON.parse(body);
        res.json({
          code: 1,
          msg: body
        })
        return;
      }
    })
  })

  // 根据用户id获取用户的专属音乐
  app.post("/getMusic", (req, res) => {
    const sql = ` select * from userdata where id=${req.body.id}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        res.json({
          code: 'M0002',
          msg: '成功查询到用户的音乐',
          data: {
            mysucId: data[0].mysucid,
            mysucUser: data[0].mysucuser
          }
        })
      }
    }
    mysqlFun(sql, obj);
  })

  // 移除用户专属音乐里面的音乐
  app.post("/DeleteMusic", (req, res) => {
    // 找到用户
    const sql = `select * from usermusic where id=${req.body.id}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        // 找到歌曲id相等的一项去掉它
        let musci = eval(data[0].musiclist);
        for (let index = 0; index < musci.length; index++) {
          let element = musci[index];
          // 找到歌曲的下标
          if (element.musicId === req.body.MusicId) {
            // 删除某个音乐的
            musci.splice(index, 1)
          }
        }
        // 得到被删除的音乐
        userMusci(JSON.stringify(musci));
      }
    }
    mysqlFun(sql, obj);
    // 把改好的音乐重新写入数据库
    function userMusci(list) {
      let sql = `UPDATE usermusic SET musiclist='${list}' WHERE id=${req.body.id}`;

      function obj(data) {
        if (data === undefined) {
          return;
        }
        if (data.length !== 0) {
          res.json({
            code: 'M0006',
            msg: '删除音乐成功',
            data: eval(list).reverse()
          })
        }
      }
      mysqlFun(sql, obj);
    }
  })
}